<template>
  <div class="pagination">
    <button :disabled="pageNo ===1" @click ="$emit('newPageNo',pageNo-1)">上一页</button>
      <button 
      v-show="startEndPage.start > 1"
      :class="{ active: pageNo === 1 }"
      @click="$emit('newPageNo', 1)"
      >1</button>

    <button v-show="startEndPage.start>2">···</button>

    <button v-for="page in startEndArr" :key="page"
    :class="{ active: pageNo === page }"
    @click="$emit('newPageNo', page)"
    >
      {{ page }}
    </button>

    <button v-show="startEndPage.end<totalPages -1">···</button>
   <button v-show="startEndPage.end < totalPages"
     :class="{ active: pageNo === totalPages }"
      @click="$emit('newPageNo', totalPages)"
    >{{ totalPages }}</button>
    <button
    :disabled="pageNo === totalPages"
    @click="$emit('newPageNo', pageNo + 1)"
    >下一页</button>

    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props:["totalPages","pageNo","continuePage","total"],
  //  mounted(){
  //   setTimeout(()=>{
  //       console.log(this.startEndPage);
  //   },2000);
  // },
  computed:{
    /* 
        永远不要把v-if 和v-for同时用在同一个元素上
    -因为v-for的优先级高于v-if
    -先遍历生成结构，然后再判断去掉某些结构，对性能来说不友好
    -解决方法：1.把v-for遍历的数据用计算数据先行过滤，2.多增添一层结构分开书写v-ift v-for
    */

   startEndArr(){
    const arr =[];
    for(var i=1;i<this.startEndPage.end;i++){
      if(i>=this.startEndPage.start){
        arr.push(i);
      }
    }
    return arr;
   },
   /* 
    totalPages:总页数,
    pageNo:当前页,
    continuePage:连续页
   */

  startEndPage(){
    const{totalPages ,pageNo,continuePage}=this;
    // 根据当前页计算连续衣
    let start = 0,
    end=0;

    //判断总页数和连续页的多少比较
    if(totalPages < continuePage){
      // 如果总页数小于连续页，起始是1和结束是总页数
      start=1;
      end=totalPages;
    } else{
      // 如果总页数大于连续页
      //首先根据当前的页码，计算出连续页的开头和连续页的结尾
      start = pageNo - Math.floor(continuePage /2);
      end = pageNo + Math.floor(continuePage /2);

      if(start <1){
        // 如果start小于1，则直接设置起始为1
        start =1;
        // 如果start已经变成1了，则直接设置end为连续页长度
        end = continuePage;
      }
      if(end > totalPages) {
        //如果end大于总页数，则直接设置end有总页数
        end=totalPages;
        start = totalPages - continuePage +1;
      }
    }
    return {start,end};
  }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
